require('dotenv').config();
const router = require('express').Router()
const path = require('path')
const fs = require('fs')
const upload = require('../common/upload.js')

const addr = (process.env.PROTOCOL || 'http://') + (process.env.HOST || 'localhost') + ':' + (process.env.PORT || '3001')

router.post('/upload', upload.single('photo'), async (req, res) => {
    let file = req.file;
    if (file == undefined) {
        res.send({
            code: -1,
            msg: '上传文件失败，请检查后再提交'
        })
    }
    else {
        if (/\.(jpe?g|png|gif|bmp|webp)/.test(file.filename)) {
            let picUrl = `/static/resources/imgs/${file.filename}`;
            res.send({
                code: 200,
                msg: '上传图片成功。',
                picUrl,
                src: `${addr}` + picUrl
            });
        }
        else {
            res.send({
                code: -1,
                msg: '选择文件是否为图片格式'
            });
        }
    }
})

router.post('/delete', async (req, res) => {
    let picUrl = req.body.picUrl;
    let dirName = req.body.dirName || 'imgs';
    if (picUrl == undefined) {
        res.send({
            code: -1,
            msg: '缺少参数'
        })
    }
    else {
        let index = picUrl.indexOf(dirName);
        if (index > -1) {
            let temp_path = path.join(__dirname, '../public/resources/', picUrl.slice(index));
            fs.unlink(temp_path, (err) => {
                if (err) {
                    res.send({
                        code: -1,
                        msg: '删除图片失败'
                    })
                }
                else {
                    res.send({
                        code: 200,
                        msg: '删除图片成功'
                    })
                }
            })
        }
        else {
            res.send({
                code: 404,
                msg: '该路径找不到图片资源。'
            })
        }
    }
})

module.exports = router;